<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\handlers\backend;

use common\handlers\BaseHandler;
use common\helper\App;
use common\models\Admin;
use yii\web\Response;

/**
 * 校验单点登录
 * @author cleverstone
 * @since ym2.0
 */
class BeforeActionValidateSSO extends BaseHandler
{
    /**
     * @param \yii\base\ActionEvent $event
     * @throws \Throwable
     */
    public function run($event)
    {
        $ssoSwitch = $this->setting->read('SYS.SYS_SSO', 1);
        $user = $this->user;

        if (!$user->isGuest && $ssoSwitch) {
            /** @var Admin $identity */
            $identity = $user->identity;
            $sessionSSOKey = $this->session->get(App::params('admin.SSO.key'), '');

            if (strcmp($identity->sso_key, $sessionSSOKey)) {
                $user->logout();

                $flashError = '账号【' . $identity->username . '】会话失效（可能原因：浏览器重启或账号已在另一处登录），请重新登录。';
                $response = $this->response;

                if ($this->request->isAjax) {
                    $response->format = Response::FORMAT_JSON;
                    $response->data = [
                        'code' => App::params('http.res.failure'),
                        'msg' => $flashError,
                    ];
                } else {
                    $response->redirect([App::params('admin.route.login')]);
                }

                $this->session->setFlash(App::params('admin.session.flash.error'), $flashError);

                $event->isValid = false;
                $event->handled = true;
            }
        }
    }
}